package cn.dansj.common.mail.bean;

import cn.dansj.common.utils.enums.GlobalEnv;
import cn.dansj.common.utils.json.JSONObject;
import cn.dansj.common.utils.transfer.DefaultMethods;
import org.thymeleaf.context.Context;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.io.Serializable;

/**
 * 邮件主体
 */
public class MailContent extends DefaultMethods implements Serializable {
    private static final long serialVersionUID = GlobalEnv.SerialVersionUID;
    private InternetAddress[] recipient;
    private InternetAddress[] ccRecipient;
    private String subject;
    private String message;
    private MailFile[] files;
    private String template = "defaultMailTemplate.html";
    private Context context;
    private boolean html = false;

    public InternetAddress[] getCcRecipient() {
        return ccRecipient;
    }

    public InternetAddress[] getRecipient() {
        return recipient;
    }

    public void setFiles(MailFile... files) {
        this.files = files;
    }

    private InternetAddress[] transformMailList(String address) {
        //地址强转为逗号分隔符形式
        address = String.join(",", address.split("[;,；， \n]"));
        InternetAddress[] internetAddressTo;
        try {
            internetAddressTo = InternetAddress.parse(address);
        } catch (AddressException e) {
            internetAddressTo = null;
        }
        return internetAddressTo;
    }

    public void setRecipient(String recipient) {
        this.recipient = transformMailList(recipient);
    }

    public void setCcRecipient(String ccRecipient) {
        this.ccRecipient = transformMailList(ccRecipient);
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public MailFile[] getFiles() {
        return files;
    }

    public String getTemplate() {
        return template;
    }

    public void setTemplate(String template) {
        this.template = template;
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public void setContext(Object... context) {
        if (this.context == null) this.context = new Context();
        this.context.setVariables(JSONObject.of(context));
    }

    public boolean isHtml() {
        return html;
    }

    public void setHtml(boolean html) {
        this.html = html;
    }
}
